using UnityEngine;

public class EnemyTankFollower : MonoBehaviour
{
    public Transform player;
    public Transform targetToRotate;

    public float lerpDuration = 1f;
    public float forwardDistance = 20f;
    public float initialTargetDistance = 40f;
    public float horizontalOffset = 0f;
    public float arriveThreshold = 0.1f;

    [Header("侧向移动设置")]
    public bool enableSideMovement = false;
    public float sideMoveRange = 3f;
    public float sideMoveSpeed = 2f;

    [Header("方向设置")]
    public bool followOppositeDirection = false;

    private enum MoveState { SinMoving, ReturningToCenter, Paused, TransitionToSin }
    private MoveState moveState = MoveState.SinMoving;

    private bool reachedInitialTarget = false;
    private float lerpTimer = 0f;
    private Vector3 startPosition;
    private Vector3 initialTargetPosition;

    private float stateTimer = 0f;
    private float sideMoveTimer = 0f;
    private float currentOffset = 0f;
    private float sinTargetOffset = 0f;

    private AutoShellShooter autoShooter;
    private ParabolaShooter parabolaShooter;


    void OnEnable()
    {
        autoShooter = GetComponent<AutoShellShooter>();
        if (autoShooter != null) autoShooter.enabled = false;

        parabolaShooter = GetComponent<ParabolaShooter>();
        if (parabolaShooter != null) parabolaShooter.enabled = false;

        if (player != null)
        {
            startPosition = transform.position;

            // 修复：只反转前进方向，不反转水平偏移
            Vector3 forwardOffset = player.forward * initialTargetDistance * (followOppositeDirection ? -1 : 1);
            Vector3 rightOffset = player.right * horizontalOffset;

            initialTargetPosition = player.position + forwardOffset + rightOffset;
            initialTargetPosition.y = 2.1f;

            currentOffset = horizontalOffset;
        }
    }

    void Update()
    {
        if (player == null) return;

        if (!reachedInitialTarget)
        {
            lerpTimer += Time.deltaTime;
            float t = Mathf.Clamp01(lerpTimer / lerpDuration);
            Vector3 lerpedPos = Vector3.Lerp(startPosition, initialTargetPosition, t);
            lerpedPos.y = 2.1f;
            transform.position = lerpedPos;

            if (Vector3.Distance(transform.position, initialTargetPosition) < arriveThreshold)
            {
                reachedInitialTarget = true;
                transform.position = initialTargetPosition;

                GetComponent<BoxCollider>().enabled = true;
                if (autoShooter != null) autoShooter.enabled = true;
                if (parabolaShooter != null) parabolaShooter.enabled = true;

                sideMoveTimer = 0f;
                stateTimer = 0f;
                currentOffset = horizontalOffset;
                moveState = MoveState.SinMoving;
            }
        }
        else
        {
            float normalizedOffset = 0f;

            if (enableSideMovement)
            {
                stateTimer += Time.deltaTime;

                switch (moveState)
                {
                    case MoveState.SinMoving:
                        sideMoveTimer += Time.deltaTime * sideMoveSpeed;
                        float sinValue = Mathf.Sin(sideMoveTimer);
                        currentOffset = horizontalOffset + sinValue * sideMoveRange;
                        normalizedOffset = sinValue;

                        if (stateTimer >= 5f)
                        {
                            stateTimer = 0f;
                            moveState = MoveState.ReturningToCenter;
                        }
                        break;

                    case MoveState.ReturningToCenter:
                        currentOffset = Mathf.Lerp(currentOffset, horizontalOffset, Time.deltaTime * 2f);
                        normalizedOffset = (currentOffset - horizontalOffset) / sideMoveRange;

                        if (Mathf.Abs(currentOffset - horizontalOffset) < 0.01f)
                        {
                            currentOffset = horizontalOffset;
                            stateTimer = 0f;
                            moveState = MoveState.Paused;
                        }
                        break;

                    case MoveState.Paused:
                        currentOffset = horizontalOffset;
                        normalizedOffset = 0f;

                        if (stateTimer >= 3f)
                        {
                            stateTimer = 0f;
                            moveState = MoveState.TransitionToSin;
                        }
                        break;

                    case MoveState.TransitionToSin:
                        float sin = Mathf.Sin(sideMoveTimer);
                        sinTargetOffset = horizontalOffset + sin * sideMoveRange;
                        currentOffset = Mathf.Lerp(currentOffset, sinTargetOffset, Time.deltaTime * 2f);
                        normalizedOffset = (currentOffset - horizontalOffset) / sideMoveRange;

                        if (Mathf.Abs(currentOffset - sinTargetOffset) < 0.05f)
                        {
                            float sinMatch = (currentOffset - horizontalOffset) / sideMoveRange;
                            sideMoveTimer = Mathf.Asin(Mathf.Clamp(sinMatch, -1f, 1f));

                            stateTimer = 0f;
                            moveState = MoveState.SinMoving;
                        }
                        break;
                }
            }

            // 修复：前进方向和水平偏移分离
            Vector3 forwardDir = player.forward * (followOppositeDirection ? -1 : 1);
            Vector3 targetPos = player.position + forwardDir * forwardDistance + player.right * currentOffset;
            targetPos.y = 2.1f;
            transform.position = targetPos;

            // 炮塔旋转
            if (targetToRotate != null)
            {
                float yAngle = Mathf.Lerp(90f, -90f, (normalizedOffset + 1f) / 2f);
                Quaternion rot = Quaternion.Euler(0f, yAngle, 0f);
                targetToRotate.localRotation = Quaternion.Slerp(targetToRotate.localRotation, rot, Time.deltaTime * 10f);
            }
        }
    }

    void OnDrawGizmosSelected()
    {
        if (player != null && enableSideMovement)
        {
            // 修复 Gizmos：和 Update 保持一致
            Vector3 forwardDir = player.forward * (followOppositeDirection ? -1 : 1);
            Vector3 basePos = player.position + forwardDir * forwardDistance + player.right * horizontalOffset;
            basePos.y = 2.1f;

            Vector3 leftLimit = basePos - player.right * sideMoveRange;
            Vector3 rightLimit = basePos + player.right * sideMoveRange;

            Gizmos.color = Color.yellow;
            Gizmos.DrawLine(leftLimit, rightLimit);
            Gizmos.DrawSphere(leftLimit, 0.3f);
            Gizmos.DrawSphere(rightLimit, 0.3f);
        }
    }
}
